package com.github.live.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.github.livebase.util.base.CollectionsUtil;

import java.util.Arrays;
import java.util.List;

public class LoadingActivity extends Activity {
    private String[] permissions = new String[]{
            Manifest.permission.INTERNET, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.CHANGE_WIFI_MULTICAST_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION//, Manifest.permission.REQUEST_INSTALL_PACKAGES
    };


    /**
     * @param requestCode 是我们自己定义的权限请求码
     * @param permissions 是我们请求的权限名称数组
     * @param grantResults 是我们在弹出页面后是否允许权限的标识数组，数组的长度对应的是权限名称数组的长度，数组的数据0表示允许权限，-1表示我们点击了禁止权限
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasPermissionDismiss = false;//有权限没有通过
        if ( 0x01 == requestCode) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == -1) {
                    hasPermissionDismiss = true;
                    break;
                }
            }

            //如果有权限没有被允许
            if (hasPermissionDismiss) {
                Dialog dialog = new Dialog(this);
                dialog.showPermissionDialog();//跳转到系统设置权限页面，或者直接关闭页面，不让他继续访问
            }
            else {
                gotoLive();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(Build.VERSION.SDK_INT >= 23){//6.0才用动态权限
            List<String> mPermissionlist = CollectionsUtil.filter(Arrays.asList(permissions), (p) -> {
                return ContextCompat.checkSelfPermission(this, p) != PackageManager.PERMISSION_GRANTED;
            });

            //申请权限
            if( mPermissionlist.size() > 0 ){//有权限没有通过，需要申请
                ActivityCompat.requestPermissions(this, permissions, 0x01);
            }
            else {
                gotoLive();
            }
        }
        else {
            gotoLive();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void gotoLive() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        Intent intent = new Intent(this, LivePlayActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }


    private class Dialog {
        private AlertDialog mPermissionDialog;
        private Activity context;
        public Dialog(Activity context){
            this.context = context;
        }
        public void showPermissionDialog() {
            if (mPermissionDialog == null) {
                mPermissionDialog = new AlertDialog.Builder(context)
                        .setMessage("已禁用权限，请手动授予")
                        .setCancelable(false)
                        .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                cancelPermissionDialog();
                                //跳转到设置权限界面
                                Intent intent = new Intent();
                                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", context.getPackageName(), null);
                                intent.setData(uri);
                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                context.startActivity(intent);
                                context.overridePendingTransition(0,0);
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //关闭页面或者做其他操作
                                context.finish();
                            }
                        })
                        .create();
            }
            mPermissionDialog.show();
        }
        /**
         * 不再提示权限时的展示对话框
         */

        //关闭对话框
        private void cancelPermissionDialog() {
            mPermissionDialog.cancel();
        }
    }
}